package com.neu.flashmall.ms.controller;


import com.neu.common.utils.Result;
import com.neu.common.utils.ValidUtil;
import com.neu.common.valid.AddGroup;
import com.neu.common.valid.UpdateGroup;
import com.neu.flashmall.ms.entity.SysMenu;
import com.neu.flashmall.ms.service.SysMenuService;
import com.neu.flashmall.ms.vo.SysMenuVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping(value = "/sysMenu")
public class SysMenuController {

    @Resource
    private SysMenuService sysMenuService;



    @GetMapping("/getMenuByRole")
    @ApiOperation("根据用户类型获取用户权限菜单接口")
    public Result getMenuByRole(Integer role){
        List<Long> menuList  = this.sysMenuService.getMenuByRole(role);
        return Result.ok().put(menuList);
    }

    @GetMapping("/getAllMenuWithLevel")
    @ApiOperation("返回已经有层级关系的SysMenuVo")
    public Result getAllMenuWithLevel(){
        SysMenuVo sysMenuVo = this.sysMenuService.createSysMenuVoLevel();
        return Result.ok().put(sysMenuVo);
    }

    @PutMapping("/check/addSysMenu")
    @ApiOperation("新建一个SysMenu")
    public Result addSysMenu(
            @RequestBody @Validated(AddGroup.class) SysMenu sysMenu,
            BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return ValidUtil.createResultByBindingResult(bindingResult);
        }
        String outcome = this.sysMenuService.addSysMenu(sysMenu);
        if(outcome.equals("添加权限成功")){
            return Result.ok().setMessage(outcome);
        }
        return Result.error().setMessage(outcome);
    }

    @DeleteMapping("/check/deleteSysMenu")
    @ApiOperation("根据id删除SysMenu，并且删除他下方所有子权限")
    public Result deleteSysMenu(Long id,Integer level){
        String outcome = this.sysMenuService.deleteSysMenu(id,level);
        if("删除权限成功".equals(outcome)){
            return Result.ok().setMessage(outcome);
        }
        return Result.error().setMessage(outcome);
    }

    @PostMapping("/check/updateSysMenu")
    @ApiOperation("更新SysMenu信息")
    public Result updateSysMenu(
            @RequestBody @Validated(UpdateGroup.class) SysMenu sysMenu,
            BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return ValidUtil.createResultByBindingResult(bindingResult);
        }
        String outcome = this.sysMenuService.updateSysMenu(sysMenu);
        if("更新权限信息成功".equals(outcome)){
            return Result.ok().setMessage(outcome);
        }
        return Result.error().setMessage(outcome);
    }
}
